/**
 * 项目名：五位一体化工安全信息平台
 * 日期：    2019-12-03 14:14:47
 * Copyright (c) 2015- joysuch-版权所有
 */

package com.joysuch.wwyt.bp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.joysuch.wwyt.bp.bean.BpStorageTankAreaAddBean;
import com.joysuch.wwyt.bp.bean.BpStorageTankAreaBean;
import com.joysuch.wwyt.bp.entity.BpDeviceFacilityCollection;
import com.joysuch.wwyt.bp.entity.BpMonitoringPointRel;
import com.joysuch.wwyt.bp.entity.BpStorageTank;
import com.joysuch.wwyt.bp.entity.BpStorageTankArea;
import com.joysuch.wwyt.bp.entity.dsl.QBpStorageTank;
import com.joysuch.wwyt.bp.entity.dto.BpStorageTankAreaDto;
import com.joysuch.wwyt.bp.entity.dto.BpStorageTankDto;
import com.joysuch.wwyt.bp.enums.DeviceFacilityTypes;
import com.joysuch.wwyt.bp.mapper.BpStorageTankAreaMapper;
import com.joysuch.wwyt.bp.mapper.BpStorageTankMapper;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpMonitoringPointRelDao;
import com.joysuch.wwyt.bp.repository.BpStorageTankAreaDao;
import com.joysuch.wwyt.bp.repository.BpStorageTankDao;
import com.joysuch.wwyt.bp.service.BpDeviceFacilityCollectionService;
import com.joysuch.wwyt.bp.service.BpStorageTankAreaService;
import com.joysuch.wwyt.bp.service.BpStorageTankService;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.service.BaseRoleDataAuthService;
import com.joysuch.wwyt.core.service.BizCodeGeneratorFacade;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.dataperm.annotation.DisableDataPermission;
import com.joysuch.wwyt.mh.bean.MhMonitoringPointBean;
import com.joysuch.wwyt.mh.entity.MhMajorHazard;
import com.joysuch.wwyt.mh.entity.MhMonitoringPoint;
import com.joysuch.wwyt.mh.repository.MhMajorHazardDao;
import com.joysuch.wwyt.mh.repository.MhMonitoringPointDao;
import com.joysuch.wwyt.mh.service.MhMonitoringPointService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.Collections.EMPTY_LIST;

@Service
@Transactional
public class BpStorageTankAreaServiceImpl implements BpStorageTankAreaService {

    @Autowired
    private BpStorageTankAreaDao dao;
    @Autowired
    private BizCodeGeneratorFacade bizCodeGeneratorFacade;
    @Autowired
    private BpMonitoringPointRelDao relDao;
    @Autowired
    private BpStorageTankDao tankDao;
    @Autowired
    private BpDeviceFacilityCollectionService bpDeviceFacilityCollectionService;
    @Autowired
    private MhMajorHazardDao mhMajorHazardDao;
    @Autowired
    private MhMonitoringPointDao mhMonitoringPointDao;
    @Autowired
    private BpStorageTankService bpStorageTankService;
    @Autowired
    private MhMonitoringPointService mhMonitoringPointService;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BpStorageTankAreaMapper storageTankAreaMapper;
    @Autowired
    private BaseRoleDataAuthService baseRoleDataAuthService;
    @Autowired
    private BpStorageTankMapper storageTankMapper;


    @Override
    public String add(BpStorageTankAreaAddBean s) {
        String errorMessage = "";
        BpStorageTankArea b = new BpStorageTankArea();
        b.setArea(s.getArea());
        if (StringUtils.isEmpty(s.getCode())) {
            b.setCode(bizCodeGeneratorFacade.chuGuanQu());
        } else {
            Assert.isTrue(dao.findByCode(s.getCode()) == null, "统一编码" + s.getCode() + "已经存在");
            b.setCode(s.getCode());
        }
        b.setCofferdamArea(s.getCofferdamArea());
        b.setHasCofferdam(s.getHasCofferdam());
        b.setHasFireChannel(s.getHasFireChannel());
        b.setInFunctionArea(s.getInFunctionArea());
        b.setIsMajorHazard(s.getIsMajorHazard());
        b.setLoadChemTypes(s.getLoadChemTypes());
        b.setLoadMethod(s.getLoadMethod());
        b.setLocation(s.getBpStorageTankArea());
        b.setMinDistance(s.getMinDistance());
        b.setName(s.getName());
        b.setNomalStorage(s.getNomalStorage());
        if (s.getMhMajorHazard() != null) {
            b.setMhMajorHazard(mhMajorHazardDao.getOne(s.getMhMajorHazard()));
        }
        b.setSafeDistance(s.getSafeDistance());
        b.setStoreMaterial(s.getStoreMaterial());
        b.setTankCount(s.getTankCount());
        b.setVolume(s.getVolume());
        b.setResponsibleDept(s.getResponsibleDept());
        BpStorageTankArea save = dao.save(b);
        List<Long> pointId = s.getPointId();
        if (pointId != null) {
            for (Long aLong : pointId) {
                String str = mhMonitoringPointService.checkMhMointPoint(aLong, save.getId());
                if (StringUtils.isNotBlank(str)) {
                    errorMessage = errorMessage + " " + str;
                }
                if (s.getExcelFlag() == null && StringUtils.isBlank(errorMessage) || (StringUtils.isBlank(errorMessage) && s.getExcelFlag() != null && s.getExcelFlag().intValue() == 1)) {
                    BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
                    bpMonitoringPointRel.setRefType("store_tank_area");
                    bpMonitoringPointRel.setRefId(save.getId());
                    bpMonitoringPointRel.setMonitoringPointId(aLong);
                    relDao.save(bpMonitoringPointRel);
                }
            }
        }
        if (s.getExcelFlag() == null && StringUtils.isBlank(errorMessage) || (StringUtils.isBlank(errorMessage) && s.getExcelFlag() != null && s.getExcelFlag().intValue() == 1)) {
            addOrUpdateDeviceFacilityCollection(save, pointId);
        }
        return errorMessage;
    }

    private void addOrUpdateDeviceFacilityCollection(BpStorageTankArea save, List<Long> pointId) {
        // 保存到集中统一的表中
        BpDeviceFacilityCollection device = bpDeviceFacilityCollectionService.addOrUpdateOtherDevice(
                DeviceFacilityTypes.CHU_GUAN_QU, save.getId(), save.getCode(), save.getName(), null,
                save.getMhMajorHazard() == null ? null : save.getMhMajorHazard().getId(), save.getLocation());
        // 绑定监测点
        bpDeviceFacilityCollectionService.bindDeviceAndMonitorPointsByIds(device, pointId);
    }


    @Override
    public String update(BpStorageTankAreaAddBean s) {
        String errorMessage = "";
        BpStorageTankArea entity = dao.findById(s.getId()).get();
        relDao.deleteByRefTypeAndRefId("store_tank_area", s.getId());
        Assert.notNull(s.getCode(), "储罐区编码不能为空");
        validateCodeUnique(s);
        entity.setCode(s.getCode());
        entity.setArea(s.getArea());
        entity.setCofferdamArea(s.getCofferdamArea());
        entity.setHasCofferdam(s.getHasCofferdam());
        entity.setHasFireChannel(s.getHasFireChannel());
        entity.setInFunctionArea(s.getInFunctionArea());
        entity.setIsMajorHazard(s.getIsMajorHazard());
        entity.setLoadChemTypes(s.getLoadChemTypes());
        entity.setLoadMethod(s.getLoadMethod());
        entity.setLocation(s.getBpStorageTankArea());
        entity.setMinDistance(s.getMinDistance());
        entity.setName(s.getName());
        entity.setNomalStorage(s.getNomalStorage());
        entity.setSafeDistance(s.getSafeDistance());
        entity.setStoreMaterial(s.getStoreMaterial());
        entity.setTankCount(s.getTankCount());
        if (s.getMhMajorHazard() != null) {
            entity.setMhMajorHazard(mhMajorHazardDao.getOne(s.getMhMajorHazard()));
        }
        entity.setVolume(s.getVolume());
        entity.setResponsibleDept(s.getResponsibleDept());
        BpStorageTankArea save = dao.save(entity);
        List<Long> pointId = s.getPointId();
        for (Long aLong : pointId) {
            String str = mhMonitoringPointService.checkMhMointPoint(aLong, save.getId());
            if (StringUtils.isNotBlank(str)) {
                errorMessage = errorMessage + " " + str;
            }
            if (s.getExcelFlag() == null && StringUtils.isBlank(errorMessage) || (StringUtils.isBlank(errorMessage) && s.getExcelFlag() != null && s.getExcelFlag().intValue() == 1)) {
                BpMonitoringPointRel bpMonitoringPointRel = new BpMonitoringPointRel();
                bpMonitoringPointRel.setRefType("store_tank_area");
                bpMonitoringPointRel.setRefId(save.getId());
                bpMonitoringPointRel.setMonitoringPointId(aLong);
                relDao.save(bpMonitoringPointRel);
            }
        }
        if (s.getExcelFlag() == null && StringUtils.isBlank(errorMessage) || (StringUtils.isBlank(errorMessage) && s.getExcelFlag() != null && s.getExcelFlag().intValue() == 1)) {
            addOrUpdateDeviceFacilityCollection(save, pointId);
        }
        return errorMessage;
    }

    private void validateCodeUnique(BpStorageTankAreaAddBean s) {
        BpStorageTankArea area = dao.findByCode(s.getCode());
        if (area != null && !area.getId().equals(s.getId())) {
            throw new IllegalArgumentException("库区编码已经存在");
        }
    }

    @Override
    public ResultBean findByPage(Pageable page) {
        List<Long> deptIds = baseRoleDataAuthService.findDepartIdsByCurUser();
        //无权限直接返回
        if (CollectionUtils.isEmpty(deptIds)) {
            return ResultBean.success(new ArrayList<>());
        }
        LambdaQueryWrapper<BpStorageTankAreaDto> queryWrapper = new QueryWrapper<BpStorageTankAreaDto>().lambda()
                .eq(BpStorageTankAreaDto::getTenentId, Context.getCurrentTenantId())
                .likeRight(BpStorageTankAreaDto::getOrgCode, Context.getCompanyCode())
                .in(BpStorageTankAreaDto::getResponsibleDept, deptIds)
                .eq(BpStorageTankAreaDto::getDeleteFlag, "0").orderByDesc(BpStorageTankAreaDto::getId);

        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BpStorageTankAreaDto> pageArea = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page.getPageNumber() + 1, page.getPageSize());
        IPage<BpStorageTankAreaDto> all = storageTankAreaMapper.selectPage(pageArea, queryWrapper);
        ArrayList<BpStorageTankAreaBean> list = new ArrayList<>();
        for (BpStorageTankAreaDto area : all.getRecords()) {
            BpStorageTankAreaBean b = new BpStorageTankAreaBean();
            b.setArea(area.getArea());
            b.setCode(area.getCode());
            b.setCofferdamArea(area.getCofferdamArea());
            b.setCreateBy(area.getCreateBy());
            b.setCreateTime(area.getCreateTime());
            b.setDeleteFlag(area.getDeleteFlag());
            b.setVolume(area.getVolume());
            b.setUpdateTime(area.getUpdateTime());
            b.setUpdateBy(area.getUpdateBy());
            b.setTenentId(area.getTenentId());
            b.setTankCount(area.getTankCount());
            b.setStoreMaterial(area.getStoreMaterial());
            b.setSafeDistance(area.getSafeDistance());
            b.setOrgCode(area.getOrgCode());
            b.setNomalStorage(area.getNomalStorage());
            b.setName(area.getName() + "(" + area.getCode() + ")");
            b.setMinDistance(area.getMinDistance());
            b.setLocation(area.getLocation());
            b.setLoadMethod(area.getLoadMethod());
            b.setLoadChemTypes(area.getLoadChemTypes());
            b.setIsMajorHazard(area.getIsMajorHazard());
            b.setInFunctionArea(area.getInFunctionArea());
            b.setId(area.getId());
            b.setHasFireChannel(area.getHasFireChannel());
            b.setHasCofferdam(area.getHasCofferdam());
            if (StringUtils.isNotBlank(area.getMajorHazardId())) {
                Optional<MhMajorHazard> optionalMh = mhMajorHazardDao.findById(Long.valueOf(area.getMajorHazardId()));
                if (optionalMh.isPresent()) {
                    MhMajorHazard mhMajorHazard = optionalMh.get();
                    b.setMhMajorHazard(mhMajorHazard.getId());
                    b.setMhMajorHazardName(mhMajorHazard.getName());
                }
            }
            LambdaQueryWrapper<BpStorageTankDto> qw = new QueryWrapper<BpStorageTankDto>().lambda()
                    .eq(BpStorageTankDto::getStorageTankAreaId, area.getId())
                    .eq(BpStorageTankDto::getDeleteFlag, "0");
            List<BpStorageTank> bpStorageTanks = new ArrayList<>();
            List<BpStorageTankDto> tanks = storageTankMapper.selectList(qw);
            if (!CollectionUtils.isEmpty(tanks)) {
                tanks.forEach(each -> {
                    BpStorageTank bpStorageTank = new BpStorageTank();
                    BeanUtils.copyProperties(each, bpStorageTank);
                    bpStorageTanks.add(bpStorageTank);
                });
            }
            b.setBpStorageTanks(bpStorageTanks);
            b.setResponsibleDept(area.getResponsibleDept());
            String deptName = bpDepartDao.getNameById(Long.valueOf(area.getResponsibleDept()));
            b.setResponsibleDeptName(deptName);
            list.add(b);
        }
        return ResultBean.pageData(list, all.getTotal());
    }

    @Override
    public IPage<BpStorageTankAreaDto> findTankAreaByPage(Pageable page, String name, Integer status) {
        List<Long> deptIds = baseRoleDataAuthService.findDepartIdsByCurUser();
        //无权限直接返回
        if (CollectionUtils.isEmpty(deptIds)) {
            return null;
        }
        LambdaQueryWrapper<BpStorageTankAreaDto> queryWrapper = new QueryWrapper<BpStorageTankAreaDto>().lambda()
                .isNull(null != status && 0 == status,BpStorageTankAreaDto::getLocation)
                .isNotNull(null != status && 1 == status,BpStorageTankAreaDto::getLocation)
                .eq(BpStorageTankAreaDto::getTenentId, Context.getCurrentTenantId())
                .likeRight(BpStorageTankAreaDto::getOrgCode, Context.getCompanyCode())
                .in(BpStorageTankAreaDto::getResponsibleDept, deptIds)
                .eq(BpStorageTankAreaDto::getDeleteFlag, "0");
        if (StringUtils.isNotBlank(name)){
            queryWrapper.and(QueryWrapper -> QueryWrapper.likeRight(BpStorageTankAreaDto::getName,name).or().likeRight(BpStorageTankAreaDto::getCode,name));
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BpStorageTankAreaDto> pageArea = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page.getPageNumber() + 1, page.getPageSize());
        return storageTankAreaMapper.selectPage(pageArea, queryWrapper);
    }

    @Override
    public List<BpStorageTankAreaDto> findAllHaveLocation() {
        List<Long> deptIds = baseRoleDataAuthService.findDepartIdsByCurUser();
        //无权限直接返回
        if (CollectionUtils.isEmpty(deptIds)) {
            return null;
        }
        LambdaQueryWrapper<BpStorageTankAreaDto> queryWrapper = new QueryWrapper<BpStorageTankAreaDto>().lambda()
                .isNotNull(BpStorageTankAreaDto::getLocation)
                .eq(BpStorageTankAreaDto::getTenentId, Context.getCurrentTenantId())
                .likeRight(BpStorageTankAreaDto::getOrgCode, Context.getCompanyCode())
                .in(BpStorageTankAreaDto::getResponsibleDept, deptIds)
                .eq(BpStorageTankAreaDto::getDeleteFlag, "0");
        return storageTankAreaMapper.selectList(queryWrapper);
    }

    @Override
    public List<BpStorageTankDto> findAllHaveLocationForTank() {
        List<BpStorageTankDto> result = new ArrayList<>();
        List<Long> deptIds = baseRoleDataAuthService.findDepartIdsByCurUser();
        //无权限直接返回
        if (CollectionUtils.isEmpty(deptIds)) {
            return result;
        }
        //先查出权限下的储罐区，在查出储罐区下的储罐
        LambdaQueryWrapper<BpStorageTankAreaDto> queryWrapper = new QueryWrapper<BpStorageTankAreaDto>().lambda()
                .eq(BpStorageTankAreaDto::getTenentId, Context.getCurrentTenantId())
                .likeRight(BpStorageTankAreaDto::getOrgCode, Context.getCompanyCode())
                .in(BpStorageTankAreaDto::getResponsibleDept, deptIds)
                .eq(BpStorageTankAreaDto::getDeleteFlag, "0");
        List<Long> tankAreaIds = storageTankAreaMapper.selectList(queryWrapper).stream().map(BpStorageTankAreaDto::getId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(tankAreaIds)){
            return result;
        }
        result = storageTankMapper.findAllHaveLocationForTank(tankAreaIds, Context.getCurrentTenantId(),Context.getCurrentOrgCode());
        return result;
    }

    @Override
    public Long getNumForHaveLocationForArea(Integer flag) {
        List<Long> deptIds = baseRoleDataAuthService.findDepartIdsByCurUser();
        //无权限直接返回
        if (CollectionUtils.isEmpty(deptIds)) {
            return 0L;
        }
        LambdaQueryWrapper<BpStorageTankAreaDto> queryWrapper = new QueryWrapper<BpStorageTankAreaDto>().lambda()
                .isNotNull(null != flag && 1 == flag,BpStorageTankAreaDto::getLocation)
                .eq(BpStorageTankAreaDto::getTenentId, Context.getCurrentTenantId())
                .likeRight(BpStorageTankAreaDto::getOrgCode, Context.getCompanyCode())
                .in(BpStorageTankAreaDto::getResponsibleDept, deptIds)
                .eq(BpStorageTankAreaDto::getDeleteFlag, "0");
        Integer num = storageTankAreaMapper.selectCount(queryWrapper);
        return Long.valueOf(num);
    }
    
    @Override
    public IPage<BpStorageTankDto> findTankByPage(Pageable page, String name, Integer status) {
        List<Long> deptIds = baseRoleDataAuthService.findDepartIdsByCurUser();
        //无权限直接返回
        if (CollectionUtils.isEmpty(deptIds)) {
            return null;
        }
        //先查出权限下的储罐区，在查出储罐区下的储罐
        LambdaQueryWrapper<BpStorageTankAreaDto> queryWrapper = new QueryWrapper<BpStorageTankAreaDto>().lambda()
                .eq(BpStorageTankAreaDto::getTenentId, Context.getCurrentTenantId())
                .likeRight(BpStorageTankAreaDto::getOrgCode, Context.getCompanyCode())
                .in(BpStorageTankAreaDto::getResponsibleDept, deptIds)
                .eq(BpStorageTankAreaDto::getDeleteFlag, "0");
        List<Long> tankAreaIds = storageTankAreaMapper.selectList(queryWrapper).stream().map(BpStorageTankAreaDto::getId).collect(Collectors.toList());
        //找出储罐
        if (CollectionUtils.isEmpty(tankAreaIds)){
            return null;
        }
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<BpStorageTankDto> pageTank = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page.getPageNumber() + 1, page.getPageSize());
        IPage<BpStorageTankDto> bpStorageTankDtoIPage = storageTankMapper.selectPageForDraw(pageTank,tankAreaIds, name,status,Context.getCurrentTenantId(),Context.getCurrentOrgCode());
        return bpStorageTankDtoIPage;
    }

    @Override
    public Long getNumForHaveLocationForTank(Integer flag) {
        List<Long> deptIds = baseRoleDataAuthService.findDepartIdsByCurUser();
        //无权限直接返回
        if (CollectionUtils.isEmpty(deptIds)) {
            return 0L;
        }
        //先查出权限下的储罐区，在查出储罐区下的储罐
        LambdaQueryWrapper<BpStorageTankAreaDto> queryWrapper = new QueryWrapper<BpStorageTankAreaDto>().lambda()
                .eq(BpStorageTankAreaDto::getTenentId, Context.getCurrentTenantId())
                .likeRight(BpStorageTankAreaDto::getOrgCode, Context.getCompanyCode())
                .in(BpStorageTankAreaDto::getResponsibleDept, deptIds)
                .eq(BpStorageTankAreaDto::getDeleteFlag, "0");
        List<Long> tankAreaIds = storageTankAreaMapper.selectList(queryWrapper).stream().map(BpStorageTankAreaDto::getId).collect(Collectors.toList());
        //找出储罐的数量
        if (CollectionUtils.isEmpty(tankAreaIds)){
            return 0L;
        }
        Integer num = storageTankMapper.selectCountForDraw(tankAreaIds, flag, Context.getCurrentTenantId(), Context.getCurrentOrgCode());
        return Long.valueOf(num);
    }

    @Override
    public void delete(Long id) {
        List<BpMonitoringPointRel> all1s = relDao.findAll();
        for (BpMonitoringPointRel bpMonitoringPointRel : all1s) {
            if (bpMonitoringPointRel.getRefId() == id && bpMonitoringPointRel.getRefType().equals("store_tank_area")) {
                relDao.delete(bpMonitoringPointRel);
            }
        }
        dao.deleteById(id);
        bpDeviceFacilityCollectionService.delteByDeviceTypeAndDeviceId(DeviceFacilityTypes.CHU_GUAN_QU, id);
    }

    @Override
    public BpStorageTankAreaBean findById(Long id) {
        Optional<BpStorageTankArea> optionalStorageArea = dao.findById(id);
        BpStorageTankAreaBean areaBean = new BpStorageTankAreaBean();
        if (optionalStorageArea.isPresent()) {
            BpStorageTankArea tankArea = optionalStorageArea.get();
            areaBean.setArea(tankArea.getArea());
            areaBean.setCode(tankArea.getCode());
            areaBean.setCofferdamArea(tankArea.getCofferdamArea());
            areaBean.setCreateBy(tankArea.getCreateBy());
            areaBean.setCreateTime(tankArea.getCreateTime());
            areaBean.setDeleteFlag(tankArea.getDeleteFlag());
            areaBean.setVolume(tankArea.getVolume());
            areaBean.setUpdateTime(tankArea.getUpdateTime());
            areaBean.setUpdateBy(tankArea.getUpdateBy());
            areaBean.setTenentId(tankArea.getTenentId());
            areaBean.setTankCount(tankArea.getTankCount());
            areaBean.setStoreMaterial(tankArea.getStoreMaterial());
            areaBean.setSafeDistance(tankArea.getSafeDistance());
            areaBean.setOrgCode(tankArea.getOrgCode());
            areaBean.setNomalStorage(tankArea.getNomalStorage());
            areaBean.setName(tankArea.getName());
            areaBean.setMinDistance(tankArea.getMinDistance());
            // areaBean.setLocation(tankArea.getLocation());
            areaBean.setTankCount(countOfTank(id));
            areaBean.setBpStorageTankArea(tankArea.getLocation());
            areaBean.setLoadMethod(tankArea.getLoadMethod());
            areaBean.setLoadChemTypes(tankArea.getLoadChemTypes());
            areaBean.setIsMajorHazard(tankArea.getIsMajorHazard());
            areaBean.setInFunctionArea(tankArea.getInFunctionArea());
            areaBean.setId(tankArea.getId());
            if (tankArea.getMhMajorHazard() != null) {
                areaBean.setMhMajorHazard(tankArea.getMhMajorHazard().getId());
                areaBean.setMhMajorHazardName(tankArea.getMhMajorHazard().getName());
            }
            areaBean.setResponsibleDept(tankArea.getResponsibleDept());
            String deptName = bpDepartDao.getNameById(Long.valueOf(tankArea.getResponsibleDept()));
            areaBean.setResponsibleDeptName(deptName);
            areaBean.setHasFireChannel(tankArea.getHasFireChannel());
            areaBean.setHasCofferdam(tankArea.getHasCofferdam());
            ArrayList<MhMonitoringPointBean> objects = new ArrayList<>();
            List<BpMonitoringPointRel> m = relDao.findByRefTypeAndRefId("store_tank_area", areaBean.getId());
            for (BpMonitoringPointRel rel : m) {
                MhMonitoringPoint one = mhMonitoringPointDao.getOne(rel.getMonitoringPointId());
                MhMonitoringPointBean mhMonitoringPointBean = new MhMonitoringPointBean();
                mhMonitoringPointBean.setId(one.getId());
                mhMonitoringPointBean.setName(one.getName());
                mhMonitoringPointBean.setRealtimeValue(one.getRealtimeValue());
                mhMonitoringPointBean.setPointCode(one.getPointCode());
                mhMonitoringPointBean.setMinitoringTypeName(one.getMhMonitoringType().getName());
                objects.add(mhMonitoringPointBean);
            }
            if (objects.isEmpty()) {
                areaBean.setMhMonitoringPointBean(EMPTY_LIST);
            }
            areaBean.setMhMonitoringPointBean(objects);
        }

        return areaBean;
    }

    private Integer countOfTank(Long id) {
        QBpStorageTank t = QBpStorageTank.bpStorageTank;
        return (int) tankDao.count(t.bpStorageTankArea.eq(id));
    }

    @Override
    @DisableDataPermission
    public BpStorageTankArea findByCode(String code) {
        return dao.findByCode(code);
    }

    /**
     * 储罐区删除功能
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        //查询罐区下所有储罐
        List<BpStorageTank> tanks = tankDao.findByBpStorageTankAreaId(id);
        if (!CollectionUtils.isEmpty(tanks)) {
            for (BpStorageTank tank : tanks) {
                bpStorageTankService.delete(tank.getId());
            }
        }
        relDao.deleteByRefTypeAndRefId("store_tank_area", id);
        dao.deleteById(id);
        bpDeviceFacilityCollectionService.delteByDeviceTypeAndDeviceId(DeviceFacilityTypes.CHU_GUAN_QU, id);
    }

}
